package rabbitMq

import "github.com/streadway/amqp"

// CreateQueue  创建一个队列
func (rabbitmq *RabbitMQ) CreateQueue(id string) error {
	ch, err := rabbitmq.Conn.Channel()
	defer ch.Close()
	if err != nil {
		return err
	}
	_, err = ch.QueueDeclare(
		id,    // name
		true,  // durable
		false, // delete when unused
		false, // exclusive
		false, // no-wait
		nil,   // arguments
	)
	if err != nil {
		return err
	}
	return nil
}

// PublishQueue 上传消息到指定的queue中
func (rabbitmq *RabbitMQ) PublishQueue(id string, body string) error {
	ch, err := rabbitmq.Conn.Channel()
	defer ch.Close()
	if err != nil {
		return err
	}
	err = ch.Publish(
		"",    // exchange
		id,    // routing key
		false, // mandatory
		false,
		amqp.Publishing{
			DeliveryMode: amqp.Persistent,
			ContentType:  "text/plain",
			Body:         []byte(body),
		})
	if err != nil {
		return err
	}
	return nil
}

// PublishMsgQueue 从队列中取出消息并且消费
func (rabbitmq *RabbitMQ) PublishMsgQueue(id string, body string) error {
	ch, err := rabbitmq.Conn.Channel()
	defer ch.Close()
	if err != nil {
		return err
	}
	err = ch.Publish(
		"",    // exchange
		id,    // routing key
		false, // mandatory
		false,
		amqp.Publishing{
			DeliveryMode: amqp.Persistent,
			ContentType:  "text/plain",
			Body:         []byte(body),
		})
	if err != nil {
		return err
	}
	return nil
}

// GetReadyCount 统计队列中预备消费的数据
func (rabbitmq *RabbitMQ) GetReadyCount(id string) (int, error) {
	count := 0
	ch, err := rabbitmq.Conn.Channel()
	defer ch.Close()
	if err != nil {
		return count, err
	}
	state, err := ch.QueueInspect(id)
	if err != nil {
		return count, err
	}
	return state.Messages, nil
}

// GetConsumCount 统计消费者／正在消费的数据
func (rabbitmq *RabbitMQ) GetConsumCount(id string) (int, error) {
	count := 0
	ch, err := rabbitmq.Conn.Channel()
	defer ch.Close()
	if err != nil {
		return count, err
	}
	state, err := ch.QueueInspect(id)
	if err != nil {
		return count, err
	}
	return state.Consumers, nil
}

// ClearQueue 清理队列
func (rabbitmq *RabbitMQ) ClearQueue(id string) (string, error) {
	ch, err := rabbitmq.Conn.Channel()
	defer ch.Close()
	if err != nil {
		return "", err
	}
	_, err = ch.QueuePurge(id, false)
	if err != nil {
		return "", err
	}
	return "Clear queue success", nil
}
